/**
 *
 */
package cn.com.rexen.rplus.sa.controller;

import cn.com.rexen.rplus.controller.CURDControllerSupport;
import cn.com.rexen.rplus.core.criteria.Criteria;
import cn.com.rexen.rplus.core.criteria.Page;
import cn.com.rexen.rplus.core.criteria.PageRequest;
import cn.com.rexen.rplus.core.criteria.Pageable;
import cn.com.rexen.rplus.core.execption.EmptyValueException;
import cn.com.rexen.rplus.core.execption.UniqueException;
import cn.com.rexen.rplus.core.service.IService;
import cn.com.rexen.rplus.core.utils.StringUtils;
import cn.com.rexen.rplus.sa.entity.Organization;
import cn.com.rexen.rplus.sa.entity.Role;
import cn.com.rexen.rplus.sa.entity.User;
import cn.com.rexen.rplus.sa.entity.UserOrganization;
import cn.com.rexen.rplus.sa.model.PageVO;
import cn.com.rexen.rplus.sa.model.RoleVO;
import cn.com.rexen.rplus.sa.model.UserVO;
import cn.com.rexen.rplus.sa.service.AppsService;
import cn.com.rexen.rplus.sa.service.OrganizationService;
import cn.com.rexen.rplus.sa.service.RoleService;
import cn.com.rexen.rplus.sa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 用户操作controller.
 * 
 * @author zhanghai
 */

@Controller
@RequestMapping(value = UserController.REQUEST_PATH)
public class UserController extends CURDControllerSupport<User,UserVO> {
    /**
     * user模块路径.
     */
    public static final String REQUEST_PATH = "user";
    /**
     * user对象.
     */
    private User user;
    /**
     * 用户service接口.
     */
    @Autowired
    private UserService userServie;

    /**
     * 角色service接口.
     */
    @Autowired
    private RoleService roleService;

    /**
     * 应用service接口.
     */
    @Autowired
    private AppsService appsService;

    @Autowired
    private OrganizationService organizationService;
    
    

    /*
     * (non-Javadoc)
     *
     * @see cn.com.rexen.rplus.controller.CURDControllerSupport#getEntity()
     */
    @Override
    public User getEntity() {
        if (user == null) {
            user = new User();
        }
        return user;
    }

    /**
     * 模块初始化.
     * 
     * @return ModelAndView.
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index() {
        ModelAndView mav = new ModelAndView("/sa/user");
        return mav;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * cn.com.rexen.rplus.controller.CURDControllerSupport#getEntityService()
     */
    @Override
    protected IService<User> getEntityService() {
        return userServie;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * cn.com.rexen.rplus.controller.CURDControllerSupport#beforeSave(javax.
     * servlet .http.HttpServletRequest, java.lang.Object,
     * org.springframework.validation.BindException,
     * org.springframework.ui.ModelMap)
     */
    @Override
    protected void beforeSave(HttpServletRequest request, HttpServletResponse response, UserVO vo,
            BindException errors, ModelMap mm) {
        user = new User();
        user.setApp(getApps());
        String userId = userServie.generateId();
        String name = vo.getName();
        user.setUsername(name);
        user.setPassword(vo.getPassword());
        user.setId(userId);
        user.setBirthday(vo.getBirthday());
        user.setContact(vo.getContact());
        user.setEmail(vo.getEmail());
        user.setLocked(vo.isLocked());
        user.setRealname(vo.getRealname());
        user.setSex(vo.getSex());
        user.setPhone(vo.getPhone());
        validata(user, response);
        List<RoleVO> roleVOList = vo.getRole();
        for (RoleVO roleVO : roleVOList) {
            String roleId = roleVO.getId();
            Role role = roleService.get(Role.class, roleId);
            user.addRole(role);
        }
        String orgid = vo.getOrgid();
        if (StringUtils.isNotEmpty(orgid)) {
            Organization organization = organizationService.get(Organization.class, orgid);
            if (organization != null)
                user.addUserOrganizations(organization);
        }

    }

    /*
     * (non-Javadoc)
     *
     * @see
     * cn.com.rexen.rplus.controller.CURDControllerSupport#doList(javax.servlet
     * .http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    public Page<User> doList(HttpServletRequest request, HttpServletResponse response) {
        Criteria criteria = userServie.getCriteria(User.class);
        String pageSize = request.getParameter("pageSize");
        String page = request.getParameter("page");
        Pageable pageable = new PageRequest(page == null ? 0 : Integer.parseInt(page), pageSize == null ? DEFAULT_PAGESIZE
                : Integer.parseInt(pageSize));
        criteria.setPageable(pageable);
        Page<User> findWithPage = userServie.findWithPage(criteria);
        return findWithPage;

    }

    /*
     * (non-Javadoc)
     *
     * @see
     * cn.com.rexen.rplus.controller.CURDControllerSupport#afterList(javax.servlet
     * .http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
     * org.springframework.ui.ModelMap, cn.com.rexen.rplus.core.criteria.Page)
     */
    @Override
    protected void afterList(HttpServletRequest request, HttpServletResponse response, ModelMap mm, Page page) {
        List<UserVO> userVOList = new ArrayList<UserVO>();
        for (Object object : page.getContent()) {
            User user = (User) object;
            List<Role> roleList = roleService.getRoleByUserId(user.getId());
            List<RoleVO> roleVOList = new ArrayList<RoleVO>();
            for (Role role : roleList) {
                RoleVO roleVO = new RoleVO(role.getId(), role.getName(), role.getParentid(), role.getParentid());
                roleVOList.add(roleVO);
            }
            UserVO userVO = new UserVO(user.getId(), user.getUsername(), roleVOList, getApps().getId());
            userVO.setBirthday(user.getBirthday());
            userVO.setContact(user.getContact());
            userVO.setEmail(user.getEmail());
            userVO.setLocked(user.isLocked());
            userVO.setPassword(user.getPassword());
            userVO.setRealname(user.getRealname());
            userVO.setSex(user.getSex());
            userVO.setPhone(user.getPhone());
            Set<UserOrganization> userOrganizations = user.getUserOrganizations();
            if(userOrganizations!=null&&userOrganizations.size()>0)
            {
                Iterator<UserOrganization> iterator = userOrganizations.iterator();
                if(iterator.hasNext()){//目前机构和用户是一对多的关系.而非多多对的关系.
                    UserOrganization next = iterator.next();
                    String organizationid = next.getId().getOrganizationid();
                    Organization organization = organizationService.get(Organization.class, organizationid);
                    userVO.setOrg(organization.getName());
                }
            }
           
            userVOList.add(userVO);
        }
        mm.addAttribute("data", userVOList);
        PageVO pageVO = new PageVO(page.getTotalPages(), page.getNumber(), page.getTotalElements());
        mm.addAttribute("page", pageVO);
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * cn.com.rexen.rplus.controller.CURDControllerSupport#onShow(javax.servlet
     * .http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
     * java.lang.Object, org.springframework.ui.ModelMap)
     */
//    @Override
    protected UserVO onShow(HttpServletRequest request, HttpServletResponse response, User o, ModelMap mm) {
        if (o == null) {
            return new UserVO();
        }
        User user = (User) o;
        List<Role> roleList = roleService.getRoleByUserId(user.getId());
        List<RoleVO> roleVOList = new ArrayList<RoleVO>();
        for (Role role : roleList) {
            RoleVO roleVO = new RoleVO(role.getId(), role.getName(), role.getParentid(), role.getParentid());
            roleVOList.add(roleVO);
        }
        UserVO userVO = new UserVO(user.getId(), user.getUsername(), roleVOList, getApps().getId());
        userVO.setBirthday(user.getBirthday());
        userVO.setContact(user.getContact());
        userVO.setEmail(user.getEmail());
        userVO.setLocked(user.isLocked());
        userVO.setPassword(user.getPassword());
        userVO.setRealname(user.getRealname());
        userVO.setSex(user.getSex());
        userVO.setPhone(user.getPhone());
        // mm.addAttribute("data", userVO);
        Set<UserOrganization> userOrganizations = user.getUserOrganizations();
        if (userOrganizations != null && userOrganizations.size() > 0) {
            Iterator<UserOrganization> iterator = userOrganizations.iterator();
            if(iterator.hasNext()){
                UserOrganization next = iterator.next();
                String organizationid = next.getId().getOrganizationid();
                Organization organization = organizationService.get(Organization.class, organizationid);
                userVO.setOrg(organization.getName());
                userVO.setOrgid(organizationid);
            }
        }
        return userVO;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * cn.com.rexen.rplus.controller.CURDControllerSupport#beforeUpdate(javax
     * .servlet.http.HttpServletRequest, java.lang.Object,
     * org.springframework.validation.BindException,
     * org.springframework.ui.ModelMap)
     */
    @Override
    protected void beforeUpdate(HttpServletRequest request, HttpServletResponse response, UserVO vo,
            BindException errors, ModelMap mm, String id) {
        user = userServie.get(User.class, id);
        if (user == null) {
            throw new IllegalArgumentException("数据库中不存在此数据对象.");
        }
        String name = vo.getName();
        User userByName = userServie.getUserByName(name);
        if(userByName!=null){
            if(!userByName.getUsername().equals(user.getUsername())){//
                throw new UniqueException("用户"+name+"重复.");
            }
        }
        String userId = id;
  
        user.setUsername(name);
        user.setId(userId);
        user.setBirthday(vo.getBirthday());
        user.setContact(vo.getContact());
        user.setEmail(vo.getEmail());
        user.setLocked(vo.isLocked());
        //user.setPassword(vo.getPassword());
        user.setSex(vo.getSex());
        user.setRealname(vo.getRealname());
        user.setPhone(vo.getPhone());
        user.getUserRoles().clear();
    
       

        List<RoleVO> roleVOList = vo.getRole();
        for (RoleVO roleVO : roleVOList) {
            String roleId = roleVO.getId();
            Role role = new Role(roleId);
            user.addRole(role);
        }
        String orgid = vo.getOrgid();
        if (StringUtils.isNotEmpty(orgid)) {
            Organization organization = organizationService.get(Organization.class, orgid);
            user.getUserOrganizations().clear();
            if (organization != null)
                user.addUserOrganizations(organization);
        }else{
            user.getUserOrganizations().clear();
        }

    }

    @Override
    public UserVO save(HttpServletRequest request, HttpServletResponse response, @RequestBody UserVO vo) {
        return super.save(request, response, vo);
    }

    private void validata(User user, HttpServletResponse response) {
        try {
            userServie.validateUnique(user);
        } catch (UniqueException e) {
            LOGGER.warn("用户记录重复,{}", user.getUsername());
            responseError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    StringUtils.connect("用户", user.getUsername(), "重复."), response);
            throw new UniqueException(e.getMessage());
        }
    }
    @RequestMapping(value = "/resetpassword/{id}", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap resetpassword(HttpServletRequest request, HttpServletResponse response, @PathVariable String id) {
        ModelMap mm = new ModelMap();
        try {
            if (StringUtils.isEmpty(id)) {
                throw new EmptyValueException();
            }
            userServie.resetUserPassword(id);
            mm.addAttribute("msg", "密码重置成功.");
            mm.addAttribute("success", true);
        } catch (Exception e) {
            e.printStackTrace();
//            responseError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "系统错误", response);
            mm.addAttribute("msg", "密码重置失败.");
            mm.addAttribute("success", false);
        }
        return mm;
    }

    // /**
    // * 通过用户父id获取用户列表.
    // *
    // * @param parentId
    // * 角色父id
    // * @return 返回资源列表的json数据.
    // */
    // @RequestMapping(value = "/{parentId}/children", method =
    // RequestMethod.GET)
    // @ResponseBody
    // public ModelMap children(@PathVariable String parentId) {
    // ModelMap mm = new ModelMap();
    // if (!StringUtils.isEmpty(parentId)) {
    // List<User> userList =
    // userServie.find(userServie.getCriteria(User.class));
    // List<UserVO> userVOList = new ArrayList<UserVO>();
    // for (Object object :userList) {
    // User user = (User) object;
    // List<Role> roleList = roleService.getRoleByUserId(user.getId());
    // List<RoleVO> roleVOList = new ArrayList<RoleVO>();
    // for (Role role : roleList) {
    // RoleVO roleVO = new RoleVO(role.getId(), role.getName(),
    // role.getParentid(), role.getParentid());
    // roleVOList.add(roleVO);
    // }
    // UserVO userVO = new UserVO(user.getId(), user.getUsername(),
    // roleVOList, getApps().getId());
    // userVOList.add(userVO);
    // }
    // mm.addAttribute("data", userVOList);
    // }
    // return mm;
    // }

}
